import { useAuthStore } from "@/store";
import type { BaseSearchModel } from "@/types";
import { Button, Form, Grid, Input, Tooltip } from "@arco-design/web-react";
import {
	IconArrowDown,
	IconArrowUp,
	IconPlus,
	IconSearch,
	IconUndo,
} from "@arco-design/web-react/icon";
import {
	type CSSProperties,
	type PropsWithChildren,
	type ReactNode,
	useState,
} from "react";
import { useListViewContext } from "../ListView/context";

export type SearchFormProps = PropsWithChildren<{
	model?: BaseSearchModel;
	placeholder?: string;
	showReset?: boolean;
	showAdd?: boolean | string;
	addTooltip?: string;
	extraButtons?: ReactNode;
	className?: string;
	style?: CSSProperties;
	onChange?: (values: BaseSearchModel) => void;
	onAdd?: () => void;
}>;

export default function SearchForm({
	model,
	placeholder = "请输入关键词",
	showReset = false,
	showAdd = false,
	addTooltip = "新增",
	extraButtons = null,
	className,
	style,
	children,
	onChange,
	onAdd,
}: SearchFormProps): ReactNode {
	const showAdvanced = !!children;
	const [isAdvancedVisible, setIsAdvancedVisible] = useState(false);

	const { isAuthorized } = useAuthStore();

	const shouldShowAdd =
		typeof showAdd === "boolean" ? showAdd : isAuthorized(showAdd as string);

	const toggleAdvanced = () => setIsAdvancedVisible((state) => !state);

	const [form] = Form.useForm<BaseSearchModel>();

	const lvContext = useListViewContext();
	const formModel = lvContext ? lvContext.searchModel : model;
	const handleChange = (values: BaseSearchModel) => {
		if (lvContext) {
			lvContext.setSearchModel(values);
		} else {
			onChange?.(values);
		}
	};

	const handleReset = () => {
		form.resetFields();
		handleChange({});
	};

	return (
		<Form
			form={form}
			initialValues={formModel}
			className={className}
			style={style}
			onSubmit={handleChange}
			onValuesChange={(_, values) => handleChange(values)}
			labelCol={{ span: 2 }}
			labelAlign="left"
		>
			<Grid.Row gutter={16}>
				<Grid.Col span={16}>
					<Input.Group>
						<Form.Item<BaseSearchModel> field={"searchText"} className="flex-1">
							<Input
								placeholder={placeholder}
								autoComplete="off"
								autoFocus
								allowClear
							/>
						</Form.Item>
						<Button htmlType="submit" icon={<IconSearch />} />
						{showReset && <Button icon={<IconUndo />} onClick={handleReset} />}
						{shouldShowAdd && (
							<Tooltip content={addTooltip}>
								<Button icon={<IconPlus />} onClick={onAdd} />
							</Tooltip>
						)}
						{extraButtons}
						{showAdvanced && (
							<Button
								icon={isAdvancedVisible ? <IconArrowUp /> : <IconArrowDown />}
								onClick={toggleAdvanced}
							>
								高级
							</Button>
						)}
					</Input.Group>
				</Grid.Col>
			</Grid.Row>
			<div
				className="mt-[2px] pt-[10px] border-t border-t-[#f1f1f1]"
				style={{ display: isAdvancedVisible ? "block" : "none" }}
			>
				{children}
			</div>
		</Form>
	);
}
